var less = require("less");
var fs = require("fs");
var ejs = require("ejs");
var svg2font = require("./svg2font.js");

function ejs2html(fontNameList, target) {
  fs.readFile(__dirname + "/svgdemo.ejs", "utf8", function(err, data) {
    if (err) {
      console.log(err);
      return false;
    }
    var ejs_string = data,
      template = ejs.compile(ejs_string),
      html = template({ fontNameList: fontNameList });
    fs.writeFile(target + "/svgdemo.html", html, function(err) {
      if (err) {
        console.log(err);
        return false
      }
      return true;
    });
  });
}

module.exports = {
  build(source, target) {
    svg2font.build(source, target).then(() => {
      less.render(fs.readFileSync(__dirname + "/svgfont.less", "utf8"), {
        globalVars: {
          "@fontNameList": svg2font.fontNameList,
          "@fontCodeList": svg2font.fontCodeList,
        }
      }, function(e, output) {
        if (output) {
          console.log("css生成成功")
          fs.writeFileSync(target + "/svgfont.css", output.css);
        } else {
          console.log("less转换css异常")
        }
      });

      ejs2html(svg2font.fontNameList, target)
    })
  }
}